# coding: utf-8


from Katana import QtCore, QtGui, UI4, QT4Widgets, QT4FormWidgets
from Katana import NodegraphAPI, Utils
from Katana import UniqueName, FormMaster
import os.path
import ScriptActions as SA
import logging
log = logging.getLogger('dsMatx_ResolveEditor')

Ver_Info = {
    1.0: u'2018.03.15, Release the first version.',
}


class dsMatX_ResolveEditor(QtGui.QWidget):

    def __init__(self, parent, node):
        """
        Initializes an instance of the class.
        """
        QtGui.QWidget.__init__(self, parent)
        self.__node = node
        nodeName = node.getName()
        Utils.UndoStack.OpenGroup('Upgrade "%s"' % nodeName)
        try:
            node.upgrade()
        except Exception as exception:
            log.exception('Error upgrading node "%s": %s' % (nodeName, str(exception)))
        finally:
            Utils.UndoStack.CloseGroup()

        locationParameter = self.__node.getParameter('location')
        locationParameter.setHintString("{'widget': 'newScenegraphLocation'}")
        matLocationParameter = self.__node.getParameter('matLocation')
        matLocationParameter.setValue(self.__node.getName(), 0)
        matLocationParameter.setHintString("{'help':'This namespace will be added on all the nodes resolved to avoid "
                                           "clashing from other dsMaterialX_Resolve nodes. It will also be set on the "
                                           "resulting NetworkMaterial namespace attribute. Remember to CTRL + MMB to "
                                           "dive inside this node for the resulting materials.'}")
        mtlXPathParameter = self.__node.getParameter('matXAsset')
        mtlXPathParameter.setHintString("{'widget': 'assetIdInput', 'help':'Select dsMaterialX XML file.', 'fileTypes': 'xml'}")
        locationPolicy = UI4.FormMaster.CreateParameterPolicy(None, locationParameter)
        matLocationPolicy = UI4.FormMaster.CreateParameterPolicy(None, matLocationParameter)
        mtlXPathPolicy = UI4.FormMaster.CreateParameterPolicy(None, mtlXPathParameter)
        widgetFactory = UI4.FormMaster.KatanaFactory.ParameterWidgetFactory
        locationWidget = widgetFactory.buildWidget(self, locationPolicy)
        matLocationWidget = widgetFactory.buildWidget(self, matLocationPolicy)
        mtlXWidget = widgetFactory.buildWidget(self, mtlXPathPolicy)


        self._infoGroup = QtGui.QGroupBox(self)
        self._infoGroup.setLayout(QtGui.QVBoxLayout())
        self._infoGroup.setTitle('Version Information')
        self._info = QtGui.QPlainTextEdit(self._infoGroup)
        self._info.setReadOnly(True)
        self._info.setPlainText(GetPlainInfo(Ver_Info))
        self._infoGroup.layout().addWidget(self._info)


        self.__resolve = QtGui.QPushButton(self)
        self.__resolve.setText('Resolve')
        mainLayout = QtGui.QVBoxLayout()
        mainLayout.addWidget(locationWidget)
        mainLayout.addWidget(matLocationWidget)
        mainLayout.addWidget(mtlXWidget)
        mainLayout.addWidget(self.__resolve)
        mainLayout.addWidget(self._infoGroup)
        self.setLayout(mainLayout)
        QtCore.QObject.connect(self.__resolve, QtCore.SIGNAL('clicked()'), self.onResolveClicked)

    def onResolveClicked(self):
        '''
        self.__node:                                        superTools.node
        self.__node.getParameter('mtlXAsset').getValue(0)   the path to XML file
        self.__node.getParameter('location').getValue(0)    the location of Assets
        self.__node.getParameter('matLocation').getValue(0) the location of XML file
        self.__node.getParameter('mode').getValue(0)        "3delight" or "arnold"
        @return:
        '''
        SA.RestoreToDefault(self.__node)

        if os.path.isfile(self.__node.getParameter('matXAsset').getValue(0)):
            SA.ResolveMatXS(self.__node,
                            self.__node.getParameter('matXAsset').getValue(0),
                            self.__node.getParameter('location').getValue(0),
                            self.__node.getParameter('matLocation').getValue(0))
        else:
            log.warning('File do not exists.')

def GetPlainInfo(info):
    result = []

    keyList = info.keys()
    keyList = sorted(keyList)

    for key in keyList:
        result.append('Ver' + str(key) + ': ' + info[key])


    return '\n'.join(result)